import React, { useState } from 'react';
import { usePagination } from 'ahooks';
import UniversalPagination from '@/components/UniversalPagination';
import { connect } from 'umi';
import SwiperCore, { Navigation, Thumbs, Autoplay } from 'swiper/core';
import type { ConnectState } from '@/models/connect';
import { message, Space, Card, Popconfirm, Button } from 'antd';
import CreateModalForm from './components/CreateModalForm';
import UpdateModalForm from './components/UpdateModalForm';
import { GridContent } from '@ant-design/pro-layout';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import tableStyle from '@/styles/publicTable.less';
SwiperCore.use([Navigation, Thumbs, Autoplay]);
import { getCategoryList, deleteCategory } from './service';
import moment from 'moment';
interface TableListProps {}

const Category: React.FC<TableListProps> = ({ currentUser }) => {
  const [refreshCount, setRefreshCount] = useState(0);
  // const [searchParams, setSearchParams] = useState({
  //   keyword: '',
  //   category_id: ''
  // })
  /**
   *  删除节点
   * @param id
   */
  const handleDelete = async (id: number) => {
    const hide = message.loading('正在删除');
    if (!id) return true;
    try {
      const res = await deleteCategory(id);
      hide();
      if (res?.success) {
        message.success('删除成功');
        setRefreshCount(refreshCount + 1);
        return true;
      } else {
        message.error('删除失败');
        return false;
      }
    } catch (error) {
      hide();
      message.error('删除失败');
      return false;
    }
  };

  /**
   *  获取数据列表
   * @param selectedRows
   */
  const fetchList = async (params: { page: number; pageSize: number }) => {
    try {
      const res = await getCategoryList({
        ...params,
      });
      if (res.success) {
        return {
          total: res.total,
          list: res.data,
        };
      } else {
        return { total: 0, list: [] };
      }
    } catch (error) {
      return { total: 0, list: [] };
    }
  };
  const columns: ProColumns[] = [
    {
      title: '分类ID',
      dataIndex: 'ID',
      hideInSearch: true,
      className: tableStyle.firstColumnPadding,
      width: '120px',
    },
    {
      title: '分类名',
      dataIndex: 'name',
      hideInSearch: true,
      className: tableStyle.firstColumnPadding,
      width: '120px',
    },
    {
      title: '创建时间',
      dataIndex: 'CreatedAt',
      width: '130px',
      align: 'center',
      hideInSearch: true,
      render: (_) => {
        return _ && moment(_).format('YYYY-MM-DD');
      },
    },
    {
      title: '创建人',
      dataIndex: 'user_info',
      width: '130px',
      align: 'center',
      hideInSearch: true,
      render: (_) => _.username,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: '90px',
      // align: 'center',
      render: (_, row) => (
        <Space direction="horizontal" style={{ width: '100%' }}>
          <UpdateModalForm formVals={row} setRefreshCount={setRefreshCount} />
          {row.ID && (
            <Popconfirm
              placement="top"
              title="确定删除嘛？"
              onCancel={() => handleDelete(row.ID)}
              cancelButtonProps={{ type: 'primary', danger: true }}
              okText="取消"
              cancelText="是的"
              okType="default"
            >
              <Button size="small" key="view" type="primary" danger>
                删除
              </Button>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];
  const { data, loading, pagination } = usePagination(
    ({ current, pageSize }) => {
      return fetchList({
        page: current,
        pageSize,
      });
    },
    {
      refreshDeps: [refreshCount],
    },
  );
  return (
    <GridContent>
      <Card bodyStyle={{ padding: '32px 24px' }}>
        <Space direction="vertical" size={32} style={{ width: '100%' }}>
          <Card
            title="分类管理"
            extra={<CreateModalForm currentUser={currentUser} setRefreshCount={setRefreshCount} />}
            bodyStyle={{ padding: 0 }}
          >
            <ProTable
              className={tableStyle.proTableFirstColumnPadding}
              columns={columns}
              loading={loading}
              dataSource={data?.list}
              rowKey="id"
              options={false}
              search={false}
              pagination={false}
            />
            <UniversalPagination pagination={pagination} total={data?.total} />
          </Card>
        </Space>
      </Card>
    </GridContent>
  );
};

export default connect(({ user }: ConnectState) => ({
  currentUser: user.currentUser,
}))(Category);
